/*
 *    Copyright 2010-2013 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.mybatis.jpetstore.web.actions;

import org.mybatis.jpetstore.domain.Cart;
import org.mybatis.jpetstore.domain.CartItem;
import org.mybatis.jpetstore.domain.Item;
import org.mybatis.jpetstore.service.CatalogService;
import org.mybatis.jpetstore.web.bean.CartBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;

/**
 * @author Eduardo Macarron
 */
@RequestMapping("/cart")
@Controller
@SessionAttributes("cartBean")
public class CartController extends AbstractController {

	private static final long serialVersionUID = -4038684592582714235L;

	private static final String VIEW_CART = "/cart/Cart";
	private static final String CHECK_OUT = "/cart/Checkout";

	@ModelAttribute
	public CartBean getCartBean(HttpSession session){
		CartBean cartBean = (CartBean)session.getAttribute("cartBean");
		if(cartBean == null){
			cartBean = new CartBean();
		}
		return cartBean;
	}
	@Autowired
	private CatalogService catalogService;

	@RequestMapping("addItemToCart")
	public String addItemToCart(@ModelAttribute CartBean cartBean) {
		Cart cart = cartBean.getCart();
		String workingItemId = cartBean.getWorkingItemId();
		if (cart.containsItemId(workingItemId)) {
			cart.incrementQuantityByItemId(workingItemId);
		} else {
			// isInStock is a "real-time" property that must be updated
			// every time an item is added to the cart, even if other
			// item details are cached.
			boolean isInStock = catalogService.isItemInStock(workingItemId);
			Item item = catalogService.getItem(workingItemId);
			cart.addItem(item, isInStock);
		}

		return (VIEW_CART);
	}

	@RequestMapping("removeItemFromCart")
	public String removeItemFromCart(@ModelAttribute CartBean cartBean, ModelMap model) {
		Cart cart = cartBean.getCart();
		String workingItemId = cartBean.getWorkingItemId();
		Item item = cart.removeItemById(workingItemId);

		if (item == null) {
			model.addAttribute("message", "Attempted to remove null CartItem from Cart.");
			return (ERROR);
		} else {
			return (VIEW_CART);
		}
	}

	@RequestMapping("updateCartQuantities")
	public String updateCartQuantities(@ModelAttribute CartBean cartBean, HttpServletRequest request) {
		Iterator<CartItem> cartItems = cartBean.getCart().getAllCartItems();
		while (cartItems.hasNext()) {
			CartItem cartItem = (CartItem) cartItems.next();
			String itemId = cartItem.getItem().getItemId();
			try {
				int quantity = Integer.parseInt((String) request.getParameter(itemId));
				cartBean.getCart().setQuantityByItemId(itemId, quantity);
				if (quantity < 1) {
					cartItems.remove();
				}
			} catch (Exception e) {
				//ignore parse exceptions on purpose
			}
		}

		return (VIEW_CART);
	}

	@RequestMapping("viewCart")
	public String viewCart() {
		return (VIEW_CART);
	}

	@RequestMapping("checkOut")
	public String checkOut() {
		return (CHECK_OUT);
	}

}
